package com.tsd.common.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.tsd.core.config.Config;
import com.tsd.core.constants.ConfigKeyConstants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.WaterMarkUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.system.controller.SystemBaseController;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 描述：Pdf操作控制层，如拆分、合并、指定页码合并
 *
 * @author zsy
 * @date 2020/12/30
 */
@Controller
@Scope("prototype")
@RequestMapping("/pdf")
public class CommonPdfController extends SystemBaseController {

    /**
     * 按顺序拆分
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/splitPdfFileOrder.action", method = RequestMethod.POST)
    public HttpResult<Object> splitPdfFileOrder(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            Document document;
            PdfCopy copy;
            Map<String, Object> map = super.getParams(request);
            // 二维码坐标
            Double positionX = HlpUtils.getDouble(map, "position_x");
            Double positionY = HlpUtils.getDouble(map, "position_y");
            PdfReader reader = new PdfReader(file.getBytes());
            // 获取目标PDF共多少页
            int n = reader.getNumberOfPages();
            // 目标文件路径
            String staticPath = Config.getParameterValue(ConfigKeyConstants.UPLOAD_ROOT_PATH);
            // 保存文件路径
            String savePath;
            // 保存二维码文件路径
            String saveMarkPath;
            // 保存文件路径数组
            ArrayList<String> savePaths = new ArrayList<String>();
            ArrayList<String> saveMarkPaths = new ArrayList<String>();
            for (int i = 1; i <= n; i++) {
                staticPath = "/" + file.getOriginalFilename();
                saveMarkPath = staticPath + staticPath + '-' + i + "-mark.pdf";
                staticPath = staticPath + staticPath + '-' + i + ".pdf";
                savePaths.add(staticPath);
                saveMarkPaths.add(saveMarkPath);
            }
            // 循环目标每页
            for (int i = 0; i < n; i++) {
                document = new Document(reader.getPageSize(1));
                copy = new PdfCopy(document, new FileOutputStream(savePaths.get(i)));
                document.open();
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, i + 1);
                copy.addPage(page);
                document.close();
                // 加二维码
                InputStream input = new FileInputStream(savePaths.get(i));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveMarkPaths.get(i)));
                WaterMarkUtils.setQrCodeForPDF(bos, input, positionX, positionY);
            }
            // 保存图纸到数据库或者输出文件流
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 按指定页码拆分
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/spitPdfFileByPages.action", method = RequestMethod.POST)
    public HttpResult<Object> spitPdfFileByPages(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            Document document;
            PdfCopy copy;
            Map<String, Object> map = super.getParams(request);
            // 二维码坐标
            Double positionX = HlpUtils.getDouble(map, "position_x");
            Double positionY = HlpUtils.getDouble(map, "position_y");
            String pageStr = HlpUtils.getString(map, "page_nums");
            super.checkEmpty(pageStr, "请提供参数page_nums");
            String[] pageNum = pageStr.split(",");
            PdfReader reader = new PdfReader(file.getBytes());
            // 获取目标PDF共多少页
            int n = reader.getNumberOfPages();
            // 目标文件路径
            String staticPath = Config.getParameterValue(ConfigKeyConstants.UPLOAD_ROOT_PATH);
            // 保存文件路径
            String savePath = "/" + file.getOriginalFilename();
            String saveMarkPath;
            StringBuilder tempStr = new StringBuilder();
            for (int i = 1; i <= pageNum.length; i++) {
                tempStr.append(pageNum[i - 1]);
                if (i != pageNum.length) {
                    tempStr.append(",");
                }
            }
            saveMarkPath = staticPath + savePath + "-" + tempStr + "-mark.pdf";
            savePath = staticPath + savePath + "-" + tempStr + ".pdf";
            // 循环目标每页
            document = new Document(reader.getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(savePath));
            document.open();
            // 拆分多页到一个PDF
            for (String num : pageNum) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, Integer.parseInt(num));
                copy.addPage(page);
            }
            document.close();
            // 加二维码
            InputStream input = new FileInputStream(new File(savePath));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(saveMarkPath)));
            WaterMarkUtils.setQrCodeForPDF(bos, input, positionX, positionY);
            // 保存图纸到数据库或者输出文件流
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 合并PDF
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/mergePdfFiles.action", method = RequestMethod.POST)
    public HttpResult<Object> mergePdfFiles() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            Map<String, Object> map = super.getParams(request);
            Object fileStr = map.get("file_list");
            if (fileStr instanceof List) {
                // 目标文件路径
                String staticPath = Config.getParameterValue(ConfigKeyConstants.UPLOAD_ROOT_PATH);
                List<String> fileList = JSONArray.parseArray(JSON.toJSONString(fileStr), String.class);
                Document document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
                String savePath = "/" + new File(fileList.get(0)).getName();
                savePath = staticPath + savePath + "-merge" + ".pdf";
                PdfCopy copy = new PdfCopy(document, Files.newOutputStream(Paths.get(savePath)));
                document.open();
                for (String s : fileList) {
                    PdfReader reader = new PdfReader(s);
                    int n = reader.getNumberOfPages();
                    for (int j = 1; j <= n; j++) {
                        document.newPage();
                        PdfImportedPage page = copy.getImportedPage(reader, j);
                        copy.addPage(page);
                    }
                }
                document.close();
                // 保存图纸到数据库或者输出文件流
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                throw new HlpException("file_list数据格式非数组类型");
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


}
